const express = require('express')
const router = express.Router()
const db = require('../db')
const auth = require('../middleware/auth')

// 获取用户资料
router.get('/:id', async (req, res) => {
  try {
    // 获取基本信息
    const [user] = await db.query(
      'SELECT id, username, email, avatar, bio FROM users WHERE id = ?', 
      [req.params.id]
    )

    // 获取文章数量
    const [articles] = await db.query(
      'SELECT COUNT(*) as count FROM articles WHERE user_id = ?',
      [req.params.id]
    )

    // 获取粉丝数量
    const [followers] = await db.query(
      'SELECT COUNT(*) as count FROM subscriptions WHERE subscribed_id = ?',
      [req.params.id]
    )

    // 获取关注数量
    const [following] = await db.query(
      'SELECT COUNT(*) as count FROM subscriptions WHERE subscriber_id = ?',
      [req.params.id]
    )
    console.log(user[0],articles[0],followers[0],following[0]);
    
    res.json({
      ...user[0],
      stats: {
        articles: articles[0].count,
        followers: followers[0].count,
        following: following[0].count
      }
    })
  } catch (error) {
    res.status(500).json({ error: '获取用户资料失败' })
  }
})

// 获取用户文章列表
router.get('/:id/articles', async (req, res) => {
  try {
    const [articles] = await db.query(
      `SELECT 
        a.id, a.title, a.content as summary, a.create_time as createTime,
        (SELECT COUNT(*) FROM comments WHERE article_id = a.id) as comments,
        (SELECT COUNT(*) FROM likes WHERE article_id = a.id) as likes,
        (SELECT SUM(view_count) FROM views WHERE article_id = a.id) as views
      FROM articles a
      WHERE a.user_id = ?
      ORDER BY a.create_time DESC`,
      [req.params.id]
    )
    console.log(articles, articles[0])
    
    res.json(articles.map(article => ({
      ...article,
      stats: {
        comments: article.comments,
        likes: article.likes,
        views: article.views || 0  // 如果没有浏览记录，返回0
      }
    })))
  } catch (error) {
    res.status(500).json({ error: '获取文章列表失败' })
  }
})

// 获取用户评论列表
router.get('/:id/comments', async (req, res) => {
  try {
    const [comments] = await db.query(
      `SELECT 
        c.id, c.content, 
        c.create_time as createTime,
        a.id as articleId, a.title as articleTitle
      FROM comments c
      JOIN articles a ON c.article_id = a.id
      WHERE c.user_id = ?
      ORDER BY c.create_time DESC`,
      [req.params.id]
    )
    console.log(comments, comments[0])
    
    res.json(comments)
  } catch (error) {
    res.status(500).json({ error: '获取评论列表失败' })
  }
})

// 获取用户点赞的文章
router.get('/:id/likes', async (req, res) => {
  try {
    const [likes] = await db.query(
      `SELECT 
        a.id, a.title, a.content as summary, 
        a.create_time as createTime,
        a.user_id as authorId,
        u.username as authorName
      FROM likes l
      LEFT JOIN articles a ON l.article_id = a.id
      LEFT JOIN users u ON a.user_id = u.id
      WHERE l.user_id = ?
      ORDER BY createTime DESC`,
      [req.params.id]
    )
    console.log(likes, likes[0])
    
    res.json(likes.map(article => ({
      ...article,
      summary: article.summary?.substring(0, 200) || ''
    })))
  } catch (error) {
    res.status(500).json({ error: '获取点赞列表失败' })
  }
})

// 获取用户扩展信息
router.get('/:id/extended', async (req, res) => {
  try {
    const [bio] = await db.query(
      'SELECT GitHub_link, Twitter_link, private_link, achievements FROM bio WHERE id = ?',
      [req.params.id]
    )
    
    res.json({
      github: bio[0]?.GitHub_link || '',
      twitter: bio[0]?.Twitter_link || '',
      website: bio[0]?.private_link || '',
      achievements: bio[0]?.achievements || ''
    })
  } catch (error) {
    res.status(500).json({ error: '获取用户扩展信息失败' })
  }
})

// 更新用户扩展信息
router.put('/:id/extended', async (req, res) => {
  try {
    const { achievements, github, twitter, website } = req.body
    
    // 检查记录是否存在
    const [existing] = await db.query(
      'SELECT id FROM bio WHERE id = ?',
      [req.params.id]
    )
    
    if (existing.length > 0) {
      // 更新现有记录
      await db.query(
        `UPDATE bio 
         SET GitHub_link = ?, 
             Twitter_link = ?, 
             private_link = ?, 
             achievements = ?
         WHERE id = ?`,
        [github, twitter, website, achievements, req.params.id]
      )
    } else {
      // 插入新记录
      await db.query(
        `INSERT INTO bio (id, GitHub_link, Twitter_link, private_link, achievements)
         VALUES (?, ?, ?, ?, ?)`,
        [req.params.id, github, twitter, website, achievements]
      )
    }
    
    res.json({ message: '更新成功' })
  } catch (error) {
    console.error('更新用户扩展信息失败:', error)
    res.status(500).json({ error: '更新用户扩展信息失败' })
  }
})

// 更新用户资料
router.put('/:id', auth, async (req, res) => {
  try {
    // 确保只能更新自己的资料
    if (req.user.id !== parseInt(req.params.id)) {
      return res.status(403).json({ error: '无权更新他人资料' })
    }

    const { bio } = req.body
    await db.query(
      'UPDATE users SET bio = ? WHERE id = ?',
      [bio, req.params.id]
    )

    res.json({ message: '更新成功' })
  } catch (error) {
    res.status(500).json({ error: '更新资料失败' })
  }
})

module.exports = router 